import Vue from 'vue'
import VueRouter from 'vue-router'

//解决路由重定向报错问题
const routerPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return routerPush.call(this, location).catch(error => error)
}

Vue.use(VueRouter)

const Login = () => import('views/login/Login')
const Home = () => import('views/home/Home')
const Welcome = () => import('views/home/Welcome')
const AlipayFill = () => import('views/fill/AlipayFill')
const MerchantList = () => import('views/merchant/MerchantList')
const AddMerchant = () => import('views/merchant/AddMerchant')

//主页下的路由
const homeChildren = [{
    path: '/welcome',
    component: Welcome
  },
  {
    path: '/alipayfill',
    component: AlipayFill
  },
  {
    path: '/merchantlist',
    component: MerchantList
  }, {
    path: '/addmerchant',
    component: AddMerchant
  }
]
const routes = [{
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: homeChildren
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

//挂载路由导航守卫
router.beforeEach((to, from, next) => {
  //to -->将要访问的路径
  //from -->从哪个路径跳转而来
  //next -->放行    next():直接放行        next('/login'):强制跳转

  //获取token
  const tokenStr = window.sessionStorage.getItem('token')
  //没有token时访问登陆页
  if (to.path == '/login' && !tokenStr) return next()
  //有token访问登陆而
  if (to.path == '/login' && tokenStr) return next('/home')
  //没有token访问其他页面
  if (!tokenStr) return next('/login')
  next()
})

export default router
